<?php

namespace KyleWechat\Wechat\Oauth;

use GuzzleHttp\Exception\GuzzleException;
use KyleWechat\Exception\InvalidParamException;
use KyleWechat\Wechat\Wechat;

class Member extends Wechat
{
    /**
     * 跳转授权
     * $options['redirect_uri'] 回调地址
     * $options['scope']   snsapi_base:静默授权   snsapi_userinfo:获取详细信息
     * @param array $options
     */
    public function authorize(array $options)
    {
        try {
            $url = $this->parseUrl('https://open.weixin.qq.com/connect/oauth2/authorize',[
                'appid' => $this->app->config->getAppid(),
                'redirect_uri' => $options['redirect_uri'],
                'response_type' => 'code',
                'scope' => $options['scope']
            ]);
            $url .= '&state=STATE#wechat_redirect';
            header("Location:{$url}");
            exit();
        } catch (\Exception $e) {
            throw new InvalidParamException($e->getMessage(),get_called_class());
        }
    }

    /**
     * 获取用户详细信息
     * @param string $openid
     * @param string $access_token
     * @param string $type userinfo|subscribe
     * @return mixed
     * @throws GuzzleException
     */
    public function userinfo(string $openid, string $access_token, string $type = 'userinfo')
    {
        $res = $this->app->config->httpClient
            ->get($this->app->config::API['wechat'][$type],[
                'access_token' => $access_token,
                'openid'       => $openid,
                'lang'         => 'zh_CN'
            ]);
        return json_decode($res,true);
    }

    public function jssdk(string $url, $access_token)
    {
        $jsapiTicket = $this->jsapi_ticket($access_token);
        $jsapi_ticket = $jsapiTicket['ticket'];
        $noncestr = $this->random(16);
        $time = time();
        $str = "jsapi_ticket={$jsapi_ticket}&noncestr={$noncestr}&timestamp={$time}&url={$url}";
        return [
            'appId' => $this->app->config->getAppid(),
            'timestamp' => $time,
            'nonceStr' => $noncestr,
            'signature' => sha1($str),
            'url' => $url,
            'rawString' => $str
        ];
    }

    private function jsapi_ticket($access_token)
    {
        $res = $this->app->config->httpClient
            ->get($this->app->config::API['wechat']['jsapi_ticket'],[
                'access_token' => $access_token,
                'type'         => 'jsapi'
            ]);
        return json_decode($res,true);
    }
}